package com.atguigu.tingshu.account.listener;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class AccountMqListener {
    @Autowired
    UserAccountService userAccountService;
    //初始化账户的消费者
    @RabbitListener(
            bindings = {
                    @QueueBinding(
                        exchange = @Exchange(value = RabbitConstant.USER_EXCHANGE ,
                        type = ExchangeTypes.TOPIC ),
                        value = @Queue(value = RabbitConstant.USER_REGISTER_QUEUE ,
                        durable = "true"),
                        key = RabbitConstant.USER_REGISTER_RK
                    )
            }
    )
    public void initAccount(Channel channel , Message message , Long userId) throws IOException {

        try {
            userAccountService.saveAccount(userId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),
                    false);
        } catch (Exception e) {
            //第一次异常 尝试重试 消费
            if(message.getMessageProperties().isRedelivered()){
                //消息多次消费异常:打印日志 并丢弃消息
                log.error("{} 执行失败, userId:{}" , "登录初始化账户信息" , userId);
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),
                        false);
            }else{
                //第一次消费失败:重新归队消费
                log.info("{} 执行失败, userId:{}，消息归队" , "登录初始化账户信息" , userId);
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                      false , true );
            }

        }
    }

}
